/*
 *  @Title LengthArrayValidator.java
 *  @Package： com.phoenix.core.annotation.impl
 *  Copyright (c) 2017 by 江苏深南互联网金融信息服务有限公司  All right reserved
 */
package com.phoenix.core.annotation.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.phoenix.core.annotation.Length;
import com.phoenix.core.util.BaseUtils;

/**
 *  @ClassName LengthArrayValidator
 *  @Description 类注释
 *  @author liuwei
 *  @version 1.0
 *  @date 2017年6月14日
 */
public class LengthArrayValidator implements ConstraintValidator<Length, String[]> {

	private int min;
	private int max;
	private boolean isEdit;

	@Override
	public void initialize(Length constraintAnnotation) {
		min = constraintAnnotation.min();
		max = constraintAnnotation.max();
		isEdit = constraintAnnotation.isEdit();
		validateParameters();
	}

	public boolean isValid(String[] value, ConstraintValidatorContext context) {
		if (value == null || value.length == 0) {
			return true;
		}
		for (String v : value) {
			// 如果是富文本编辑器，去掉这些符号
			if (isEdit) {
				String str = BaseUtils.replaceSymbolsHtml(v);
				String regEx = "<.+?>"; // 表示标签
				Pattern p = Pattern.compile(regEx);
				Matcher m = p.matcher(str);
				v = m.replaceAll("");
				max += 1000;
			}
			int length = v.length();
			if (length < min || length > max) {
				return false;
			}
		}
		return true;
	}

	private void validateParameters() {
		if (min < 0) {
			throw new IllegalArgumentException("The min parameter cannot be negative.");
		}
		if (max < 0) {
			throw new IllegalArgumentException("The max parameter cannot be negative.");
		}
		if (max < min) {
			throw new IllegalArgumentException("The length cannot be negative.");
		}
	}

}
